<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Rag Hu
 * Created Time: 2019/6/28 13:58
 * Modified Time: 2019/6/28 13:58
 * Version: 2.0
 */

namespace App\Modules\Store\Controllers;


use App\Lib\Facades\FLAuth;
use Flower\Core\Http\BaseController;
use Illuminate\Http\Request;
use App\Modules\Store\Services\RenewalService;
use Flower\Core\Repository\Exceptions\ValidatorException;
use Yansongda\Pay\Pay;
use Yansongda\Pay\Log;


class RenewalController extends BaseController
{
    protected $renewalService;

    private $AliPayConfig = [
        'app_id' => '',
        'notify_url' => 'http://app.huaxianling.com/api/notify',
        'return_url' => 'http://app.huaxianling.com/api/return',
        'ali_public_key' => '',
        'private_key' => '',
        'log' => [ // optional
            'file' => 'logs/alipay.log',
            'level' => 'debug', // 建议生产环境等级调整为 info，开发环境为 debug
            'type' => 'single', // optional, 可选 daily.
            'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
        ],
        'http' => [ // optional
            'timeout' => 5.0,
            'connect_timeout' => 5.0,
            // 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
        ],
        'mode' => 'dev', // optional,设置此参数，将进入沙箱模式
    ];

    public function __construct(RenewalService $renewalService)
    {
        $this->renewalService = $renewalService;
        $this->AliPayConfig['app_id'] = config('alipay.app_id');
        $this->AliPayConfig['ali_public_key'] = config('alipay.ali_public_key');
        $this->AliPayConfig['private_key'] = config('alipay.private_key');
        $this->AliPayConfig['log']['file'] = storage_path().'/logs/alipay.log';
    }

    /*
     * 获取续费规则
     */
    public function getRenewalRule(Request $request)
    {
        $user_id = FLAuth::id();
        $store_id = $request->input('store_id');
        $data = $this->renewalService->getRenewalRule($user_id,$store_id);


        return $this->display($data, '返回成功');

    }

    /**
     * 获取剩余服务天数
     * @param Request $request
     * @return mixed
     */
    public function getServiceRemainingDays(Request $request)
    {
        $user_id = FLAuth::id();
        $store_id = $request->input('store_id');
        $data = $this->renewalService->getServiceRemainingDays($user_id,$store_id);


        return $this->display($data, '返回成功');
    }

    /*
     * 提交订单
     */
    public function renewalAlipay(Request $request)
    {
        $user_id = FLAuth::id();
        $total_amount = $request->input('total_amount');
        $years = $request->input('years');
        //生成订单
        $order = $this->renewalService->renewalAlipay($user_id,$total_amount,$years);

        $alipay = Pay::alipay($this->AliPayConfig)->app($order);

        return $this->display($alipay->getContent(), '成功');

    }

    /*
     * 支付宝支付验签
     */
    public function renewalNotifyAlipay(Request $request)
    {

        $alipay = Pay::alipay($this->AliPayConfig);

        $trade_status = $request->input('trade_status');
        $out_trade_no = $request->input('out_trade_no');
        $total_amount = $request->input('total_amount');
        $app_id = $request->input('app_id');

        try {
            $data = $alipay->verify(); // 是的，验签就这么简单！

            // 请自行对 trade_status 进行判断及其它逻辑进行判断，在支付宝的业务通知中，只有交易通知状态为 TRADE_SUCCESS 或 TRADE_FINISHED 时，支付宝才会认定为买家付款成功。
            // 1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号；
            // 2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额）；
            // 3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）；
            // 4、验证app_id是否为该商户本身。
            // 5、其它业务逻辑情况
            $this->renewalService->notifyAlipay($trade_status,$out_trade_no,$total_amount,$app_id);

            Log::debug('Alipay notify', $data->all());

        } catch (ValidatorException $ex) {
            $msg = array_values($ex->getMessageBag()->getMessages())[0][0];
            return $this->error($msg);
        }

        return $alipay->success();// laravel 框架中请直接 `return $alipay->success()`

    }

}